package sk.mka.phd.googleagent.query;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;

/**
 *
 * @author bracek
 * @date Aug 2, 2010
 */
public abstract class AbstractGoogleQuery implements IGoogleQuery {

    protected static final String USERS_IP_ADDRESS = "192.168.1.137";
    protected static final String MY_PRIVATE_GOOGLE_KEY = "ABQIAAAAwrDY5_HxfM6jnkoTzx8RIBR0TRJkBGvJ6nYVGkP80NshstFSdBQybbQFjLiQn5AxItNj5XROWUPLjg";
    private static final Logger log = Logger.getLogger(AbstractGoogleQuery.class);
    private static String URLHEADER = "\"unescapedUrl\":\"";
    private static String TITLEHEADER = "\"titleNoFormatting\":\"";
    public static final String REQUEST_VALUE = "Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.8.1.6) Gecko/20070723 Iceweasel/2.0.0.6 (Debian-2.0.0.6-0etch1)";
    static int index = 0;

    protected final List<GoogleResult> processResult(String resultset) {
        List<GoogleResult> searchResults = new ArrayList<GoogleResult>();
        StringTokenizer stringTokenizer = new StringTokenizer(resultset, ",{");
        String next;

        String url = null;
        String title = null;

        if (stringTokenizer != null) {
            while (stringTokenizer.hasMoreTokens()) {
                next = stringTokenizer.nextToken();

                if (next.startsWith(URLHEADER)) {
                    url = next.substring(URLHEADER.length(), next.length() - 1);


                } else if (next.startsWith(TITLEHEADER)) {
                    title = next.substring(TITLEHEADER.length(), next.length() - 1);

                }

                if (url != null & title != null) {

                    searchResults.add(new GoogleResult(title, url));
                    url = null;
                    title = null;

                }
            }
        }
        return searchResults;
    }

    protected void printCountRequest() {
        AbstractGoogleQuery.index++;
        log.info(AbstractGoogleQuery.index);
    }

    @Override
    public abstract String makeQuery(String query);
}
